﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using Microsoft.Scripting.Hosting;

namespace Pahan.McuFusion.Scripting
{
    /// <summary>
    /// Script Host.
    /// </summary>
    public class McuFusionScriptHost
    {
        /// <summary>
        /// Creates a new instance.
        /// </summary>
        public McuFusionScriptHost()
        {
            ScriptRuntimeSetup setup = ScriptRuntimeSetup.ReadConfiguration();
            setup.PrivateBinding = true;
            dlrRuntime = new ScriptRuntime(setup);
        }

        /// <summary>
        /// Gets the instance of the script engine with the language specified name.
        /// </summary>
        public McuFusionScriptEngine GetEngine(String name)
        {
            var dlrEngine = dlrRuntime.GetEngine(name);
            return new McuFusionDlrScriptEngine(dlrEngine);
        }

        /// <summary>
        /// Gets instance of the script engine by script file extension.
        /// </summary>
        public McuFusionScriptEngine GetByFileExtension(String extension)
        {
            var dlrEngine = dlrRuntime.GetEngineByFileExtension(extension);
            return new McuFusionDlrScriptEngine(dlrEngine);
        }

        /// <summary>
        /// Gets the list of supported languages.
        /// </summary>
        public IList<LanguageDescriptor> SupportedLanguages
        {
            get
            {
                if (supportedLanguages == null)
                {
                    var languages = new List<LanguageDescriptor>();
                    foreach (var language in dlrRuntime.Setup.LanguageSetups)
                    {
                        languages.Add(new LanguageDescriptor()
                                      {
                                          DisplayName = language.DisplayName,
                                          Names = language.Names,
                                          Extensions = language.FileExtensions
                                      });
                    }
                    supportedLanguages = new ReadOnlyCollection<LanguageDescriptor>(languages);
                }
                return supportedLanguages;
            }
        }

        private readonly ScriptRuntime dlrRuntime;

        private IList<LanguageDescriptor> supportedLanguages;
    }
}
